package com.echo.register.controller;

import com.echo.register.commons.PadcVoteUri;
import com.echo.register.commons.excel.ExportExcelService;
import com.echo.register.commons.proto.*;
import com.echo.register.commons.result.RetCode;
import com.echo.register.commons.web.VoteBaseController;
import com.echo.register.service.CadidateService;
import com.echo.register.service.LoginService;
import com.echo.register.service.VoteSerivce;
import lombok.extern.slf4j.Slf4j;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@Slf4j
@Controller
public class VoteController extends VoteBaseController {

    @Autowired
    VoteSerivce voteSerivce;
    @Autowired
    LoginService loginService;
    @Autowired
    CadidateService cadidateService;
    @Autowired
    ExportExcelService exportExcelService;

    @RequestMapping(value = "/")
    public ModelAndView index(ModelAndView modelAndView, HttpServletRequest request, String openId) {
        return new ModelAndView("redirect:/toIndex.do");
    }

    @RequestMapping(value = "/toIndex.do")
    public String toIndex(ModelAndView modelAndView, Model model, HttpServletRequest request) {
        return "index";
    }

    @RequestMapping(value = PadcVoteUri.USER_LOGIN)
    @ResponseBody
    public LoginResp getLogin(HttpServletRequest request, HttpServletResponse response, LoginReq loginReq) {
        LoginResp loginResp = new LoginResp();
        loginResp = loginService.loginRecord(request, response, loginReq);
        if (!loginResp.getFlag().equals(RetCode.SUCCESS)) {
            return super.respFail(loginResp, loginResp.getMsg());
        }
        return super.respSuccess(loginResp);
    }

    @RequestMapping(value = PadcVoteUri.INFO_SHOWINFO, method = RequestMethod.POST)
    @ResponseBody
    public ShowInfoResp showInfo(HttpServletRequest request, HttpServletResponse response, ShowInfoReq showInfoReq) {
        ShowInfoResp showInfoResp = new ShowInfoResp();
        List<ShowInfoRespInfoGroup> showInfoRespInfoGroups = cadidateService.showDetail(showInfoReq);
        showInfoResp.setInfoGroup(showInfoRespInfoGroups);
        return super.respSuccess(showInfoResp);
    }

//    @RequestMapping(value = PadcVoteUri.INFO_VOTE)
//    @ResponseBody
//    public WebAsyncTask<VoteResp> vote(VoteReq voteReq) {
//        logger.info(Thread.currentThread().getName() + " 进入VoteController方法");
//        Cookie cookie = CookieHolder.get();
//
//        WebAsyncTask<VoteResp> webAsyncTask = new WebAsyncTask<>(3000, new Callable<VoteResp>() {
//            @Override
//            public VoteResp call() throws Exception {
//                VoteResp voteResp = new VoteResp();
//                logger.info("CookieHolder.get() is {}", cookie);
//                if (cookie == null) {
//                    voteResp.setMsg(RetCode.GetMsg(RetCode.FAIL_COOKIE));
//                    voteResp.setFlag(RetCode.FAIL_COOKIE);
//                    logger.error("没有获取到cookie");
//                    return voteResp;
//                }
//                logger.info("进入voteservice 类");
//                voteResp = voteSerivce.vote(voteReq, cookie);
//                logger.info("退出voteservice 类");
//                return VoteController.super.respFor(voteResp, voteResp.getFlag(), voteResp.getMsg());
//            }
//        });
//        logger.info(Thread.currentThread().getName() + " 从VoteController方法返回");
//
//        webAsyncTask.onCompletion(new Runnable() {
//
//            @Override
//            public void run() {
//                logger.info(Thread.currentThread().getName() + " 执行完毕");
//            }
//        });
//
//        webAsyncTask.onTimeout(new Callable<VoteResp>() {
//            @Override
//            public VoteResp call() throws Exception {
//                logger.info(Thread.currentThread().getName() + " onTimeout");
//                // 超时的时候，直接抛异常，让外层统一处理超时异常
//                throw new TimeoutException("调用超时");
//
//            }
//        });
//
//        return  webAsyncTask;
//
//    }

    @RequestMapping(value = PadcVoteUri.INFO_VOTE)
    @ResponseBody
    public VoteResp vote(HttpServletRequest request, VoteReq voteReq){
        VoteResp voteResp = voteSerivce.vote(request, voteReq);
        logger.info(voteResp.toString());
        return super.respFor(voteResp, voteResp.getFlag(), voteResp.getMsg());
    }

    @RequestMapping(value = "/info/getCVS.do")
    @ResponseBody
    public String exprotCVS(HttpServletRequest request, HttpServletResponse response) {
        if (voteSerivce.exportCVS())
            return "导出成功";
        return "导出失败";
    }

    @RequestMapping(value = "/info/getExcel.do")
    @ResponseBody
    public String exprotExcel(HttpServletRequest request, HttpServletResponse response) {
        try{
            exportExcelService.exportData(response);
        }catch (Exception e){
            return "失败";
        }
        return "成功";
    }

    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void excel(HttpServletResponse response) throws IOException{

        /**
         * excel导出
         * 1.获取数据集List 插入到map集合中
         * 2.根据模板生成新的excel
         * 3.将新生成的excel文件从浏览器输出
         * 4.删除新生成的模板文件
         */
        List<User> list = new ArrayList();
        list.add(new User(1, "zs", 21, new Date()));
        list.add(new User(2, "ls", 22, new Date()));
        Map<String, Object> beans = new HashMap();
        beans.put("list", list);

        //加载excel模板文件
        File file = null;
        try {
            file = ResourceUtils.getFile("classpath:excel/aaa.xlsx");
        } catch (FileNotFoundException e) {
            log.error("template file path cannot be found");
        }

        //配置下载路径
        String path = "/download/";
        createDir(new File(path));

        //根据模板生成新的excel
        File excelFile = createNewFile(beans, file, path);

        //浏览器端下载文件
        downloadFile(response, excelFile);

        //删除服务器生成文件
        deleteFile(excelFile);

    }


    /**
     * 根据excel模板生成新的excel
     *
     * @param beans
     * @param file
     * @param path
     * @return
     */
    private File createNewFile(Map<String, Object> beans, File file, String path) throws IOException{
        XLSTransformer transformer = new XLSTransformer();

        //可以写工具类来生成命名规则
        String name = "bbb.xlsx";
        //File newFile = new File(path + name);
        //生成的导出文件
        File destFile = File.createTempFile("bbb", ".xls");



        try (InputStream in = new BufferedInputStream(new FileInputStream(file));
             OutputStream out = new FileOutputStream(destFile)) {
            Workbook workbook = transformer.transformXLS(in, beans);
            workbook.write(out);
            out.flush();
            return destFile;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return destFile;
    }

    /**
     * 将服务器新生成的excel从浏览器下载
     *
     * @param response
     * @param excelFile
     */
    private void downloadFile(HttpServletResponse response, File excelFile) {
        /* 设置文件ContentType类型，这样设置，会自动判断下载文件类型 */
        response.setContentType("multipart/form-data");
        /* 设置文件头：最后一个参数是设置下载文件名 */
        response.setHeader("Content-Disposition", "attachment;filename=" + excelFile.getName());
        try (
                InputStream ins = new FileInputStream(excelFile);
                OutputStream os = response.getOutputStream()
        ) {
            byte[] b = new byte[1024];
            int len;
            while ((len = ins.read(b)) > 0) {
                os.write(b, 0, len);
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    /**
     * 浏览器下载完成之后删除服务器生成的文件
     * 也可以设置定时任务去删除服务器文件
     *
     * @param excelFile
     */
    private void deleteFile(File excelFile) {

        excelFile.delete();
    }

    //如果目录不存在创建目录 存在则不创建
    private void createDir(File file) {
        if (!file.exists()) {
            file.mkdirs();
        }
    }
}
